import requests
import json
import prettytable as pt    # 格式化输出（表格）

# 1，搜索功能
    # https://c.y.qq.com/soso/fcgi-bin/client_search_cp?p=1&n=10&w=

name = input("请输入歌手名称：")
url = f'https://c.y.qq.com/soso/fcgi-bin/client_search_cp?p=1&n=10&w={name}'
head = {
    'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/99.0.4844.51 Safari/537.36'
}

resp = requests.get(url)
json_str = resp.text


# 创建表格
tb = pt.PrettyTable()
tb.field_names = ['序号', '歌名', '歌手', '专辑']       # 添加表头

# 解析数据
json_dict = json.loads(json_str[9:-1])  # 类型转变
# print(json_dict)

song_list = json_dict['data']['song']['list']
index = 1
for song in song_list:
    # print(song['songmid'])
    # print(song['songname'])
    # print(song['singer'][0]['name'])
    # print(song['albumname'])
    songmid = song['songmid']
    songname = song['songname']
    singer = song['singer'][0]['name']
    albumname = song['albumname']
    # 格式化输出
    tb.add_row([index, songname , singer , albumname])    # 添加数据
    index += 1
# print(song_list)
print(tb)
# 2，下载歌曲